import { Form, Input, Button } from 'antd';
import { UserOutlined, LockOutlined,PhoneOutlined,EyeTwoTone,EyeInvisibleOutlined} from '@ant-design/icons';
import {useState} from 'react'
import { message } from "antd";
import { validate,reset} from '@/api/service/userService';
import { useNavigate} from 'react-router-dom';

const bg={
    display: 'flex', 
    justifyContent: 'center', 
    alignItems: 'center', 
    height: '100vh', 
    backgroundImage: 'linear-gradient(to right, #9fe1fa, #f4edc9)'
}

const reset_card={
    width: '400px', 
    padding: '24px', 
    backgroundColor: 'white', 
    borderRadius: '8px', 
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' 
}

export default function Reset(){
const [form] = Form.useForm();
const [messageApi, contextHolder] = message.useMessage();
const iconRender = (visible:Boolean) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)
const [time, setTime] = useState(60)
const [isShowCode, setIsShowCode] = useState<boolean>(false)
const navigate = useNavigate()

// 发送手机验证码
  const sendEmail =async () => {
    try {
      const phone=await form.validateFields(['phone'])
      if (isShowCode) { // 倒计时未结束,不能重复点击
      return
     }
    setIsShowCode(true)
    // 倒计时
    const timeId = setInterval(() => {
      setTime((preSecond) => {
        if (preSecond <= 1) {
          setIsShowCode(false)
          clearInterval(timeId)
          // 重置秒数
          return 60
        }
        return preSecond - 1
      })
    }, 1000)
  
     // 进行接口请求
      validate(phone).then(result => {
      console.log(result);
      // 登录成功给提示信息
      messageApi.open({
        type: 'success',
        content: `发送成功,请填写收到的验证码,你的验证码是:${result.code}！`,
      })
    }).catch(err => {
      //修改失败给提示信息
      messageApi.open({
        type: 'error',
        content: err.message,
      });
    })   
    } catch (error) {
       console.error('Phone validation failed:', error);
    }
  }

  const onFinish = (values: any) => {
    // 进行接口请求
    reset(values).then(result => {
      console.log(result);
      // 登录成功给提示信息
      messageApi.open({
        type: 'success',
        content: '修改成功,请重新登录！',
      }).then(() => {
        // 跳转到登录界面
        navigate("/login")
      })
    }).catch(err => {
      // 修改失败给提示信息
      messageApi.open({
        type: 'error',
        content: err.message,
      });

    })
  };

    return (
     <div style={bg}>
      {/* 提示框 */}
      {contextHolder}
      <div style={reset_card}>
        <h2 style={{ textAlign: 'center' }}>重置密码</h2>
        <Form
          name="reset"
          form={form}
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '用户名不能为空!' },
                    { pattern: /^[a-zA-Z][a-zA-Z0-9_-]{5,19}$/, message: '6至20位，以字母开头，允许字母、数字、减号、下划线' }]}
                    hasFeedback
          >
            <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
          </Form.Item>
             <Form.Item
            name="phone"
            rules={[{ required: true, message: '手机号不能为空!' },
            {pattern: /^1[3-9]\d{9}$/, message: '请输入11位手机号!' },
           ]}
            hasFeedback
          >
            <Input prefix={<PhoneOutlined />} placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="newPwd"
            rules={[
            { required: true, message: '新密码不能为空!' },
            { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,20}$/, message: '最少6位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符' }
            ]}
            hasFeedback
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入新密码"
              iconRender={iconRender}
            />
          </Form.Item>
         <Form.Item
            name="confirmPwd"
            rules={[
            { required: true, message: '确认密码不能为空!' },
            ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPwd') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('与新密码不一致,请重新输入'));
                },
              }),
            ]}
            hasFeedback
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请确认新密码"
              iconRender={iconRender}
            />
          </Form.Item>
           <Form.Item
            name='code'
            rules={[
              { required: true, message: '验证码不能为空！' },
            ]}
          >
            <Input
              placeholder='请输入手机验证码'
              suffix={<a onClick={() => sendEmail()}>
                {isShowCode ? `${time}秒后重新发送` : '发送验证码'}
              </a>}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
              确认修改
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>     
    )
}




